package org.keyroy.map_editor.ui.layouts;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager2;

public class GridFlowLayout implements LayoutManager2, java.io.Serializable {
	private static final long serialVersionUID = 1L;

	private int columns;
	private int pWidth, pHeight;

	public GridFlowLayout(int columns) {
		if (columns == 0) {
			this.columns = 1;
		} else {
			this.columns = columns;
		}
	}

	public GridFlowLayout(int columns, int pWidth, int pHeight) {
		this(columns);
		this.pWidth = pWidth;
		this.pHeight = pHeight;
	}

	@Override
	public void layoutContainer(Container parent) {
		if (pWidth == 0 || pHeight == 0) {
			int size = parent.getWidth() / columns;
			pWidth = size;
			pHeight = size;
		}

		for (int i = 0; i < parent.getComponentCount(); i++) {
			Component component = parent.getComponent(i);
			int x = i % columns;
			int y = i / columns;

			component.setBounds(x * pWidth, y * pHeight, pWidth, pHeight);
		}

	}

	@Override
	public Dimension preferredLayoutSize(Container parent) {
		Dimension dimension = new Dimension();
		int rows = parent.getComponentCount() / columns;
		if (rows % columns != 0) {
			rows += 1;
		}

		dimension.width = parent.getWidth();
		dimension.height = rows * parent.getWidth() / columns;
		return dimension;
	}

	// ***************************************************************************

	@Override
	public Dimension maximumLayoutSize(Container target) {
		return target.getSize();
	}

	@Override
	public Dimension minimumLayoutSize(Container parent) {
		return parent.getSize();
	}

	@Override
	public float getLayoutAlignmentX(Container target) {
		return 0;
	}

	@Override
	public float getLayoutAlignmentY(Container target) {
		return 0;
	}

	@Override
	public void removeLayoutComponent(Component comp) {
	}

	@Override
	public void addLayoutComponent(Component comp, Object constraints) {
	}

	@Override
	public void invalidateLayout(Container target) {
	}

	@Override
	public void addLayoutComponent(String name, Component comp) {
	}

}
